package com.threegroup.admin.controller;

import com.threegroup.admin.annotation.AuthorityVerify.AuthorityVerify;
import com.threegroup.admin.dto.SysMenuDTO;
import com.threegroup.admin.enums.MenuTypeEnum;
import com.threegroup.admin.security.user.SecurityUser;
import com.threegroup.admin.service.ISysMenuService;
import com.threegroup.common.utils.JsonUtils;
import com.threegroup.common.utils.Result;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜单管理
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Resource
    private ISysMenuService sysMenuService;

    @GetMapping("nav")
    public Result<List<SysMenuDTO>> nav(){

        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<SysMenuDTO> list = sysMenuService.getUserMenuList(user, MenuTypeEnum.MENU.value());

        return new Result<List<SysMenuDTO>>().ok(list);
    }

    /**
     * 获取权限
     * @return
     */
    @GetMapping("/permissions")
    public Result<Set<String>> getPermission() {

        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<? extends GrantedAuthority> permissions = user.getAuthorities();
        Set<String> permissionSet = permissions.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());

        return new Result<Set<String>>().ok(permissionSet);
    }

    @AuthorityVerify("sys:menu:select")
    @GetMapping("/select")
    public Result<List<SysMenuDTO>> selectMenu() {
        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        List<SysMenuDTO> userMenuList = sysMenuService.getUserMenuList(user, null);
        return new Result<List<SysMenuDTO>>().ok(userMenuList);
    }
}
